/**
 * 
 */
package com.sl.log;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;


/**
 * @author lunshi
 * TODO 為controller中的方法在使用了@RequestLogPrint註解打印請求日誌和請求耗時
 * @创建时间 2020 2020年3月10日 下午1:59:52
 * @email:shilun217@qq.com
 */
public class PrintLogInterceptor extends HandlerInterceptorAdapter{
	
	private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<Long>();
	
	private Logger logger = LoggerFactory.getLogger(PrintLogInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod handlerMethod =(HandlerMethod)handler;
		Method method = handlerMethod.getMethod();
		RequestLogPrint annotation = method.getAnnotation(RequestLogPrint.class);
		if(annotation!=null) {
			startTimeThreadLocal.set(System.currentTimeMillis());
		}
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		HandlerMethod handlerMethod =(HandlerMethod)handler;
		Method method = handlerMethod.getMethod();
		RequestLogPrint annotation = method.getAnnotation(RequestLogPrint.class);
		if(annotation!=null) {
			long expendTime=System.currentTimeMillis()-startTimeThreadLocal.get();
			//要打印的参数
			String desc = annotation.desc();
			String requestIp =request.getRequestURL().toString();
			String requestUri = request.getRequestURI();
			String methodName = method.getDeclaringClass().getName()+"#"+method.getName();
			String parameters = JSON.toJSONString(request.getParameterMap());
			logger.info("\\n描述：{},ip: {},路径: {},方法: {},n耗时：{},請求参数：{}"
					,desc,requestIp,requestUri,methodName,expendTime,parameters);
		}
	}
}
